//
// Created by mio on 25-5-9.
//

#include "TcpClient.h"

#include <cstring>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>

TcpClient::TcpClient() : sockfd_(-1), file_(nullptr), isConnect(false)
{

}

TcpClient::~TcpClient()
{
    Close();
}

void TcpClient::Create()
{
    file_ = fopen("/proc/meminfo", "r");
    if (!file_)
    {
        printf("Open File Failed\n");
        return;
    }
    memset(&info_, 0 , sizeof(info_));

    sysinfo(&info_);
    sockfd_ = socket(AF_INET, SOCK_STREAM, 0);
    Monitor_info_.SetIp("127.0.0.1");
    Monitor_info_.port = 9867;
}

bool TcpClient::Connect(std::string ip, uint16_t port)
{
    sockaddr_in addr = { 0 };
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = inet_addr(ip.c_str());

    if (connect(sockfd_, (sockaddr*)&addr, sizeof(sockaddr_in)) == -1)
    {
        printf("connect error\n");
        return false;
    }
    isConnect = true;
    return true;
}

void TcpClient::Close()
{
    isConnect = false;
    fclose(file_);
    if (sockfd_)
    {
        close(sockfd_);
    }
}

void TcpClient::GetMonitorInfo()
{
    size_t bytes_used;
    size_t read;
    char* line = nullptr;
    int index = 0;
    int avimem = 0;

    while (read = getline(&line, &bytes_used, file_) != -1)
    {
        if (++index <= 2) continue;
        if (strstr(line, "MemAvailable") != nullptr)
        {
            sscanf(line, "%*s%d%*s", &avimem);
            break;
        }
    }

    int t = info_.totalram / 1024.0;
    double mem = (t - avimem) * 100 / t;
    Monitor_info_.mem = (uint8_t)mem;
    Send((uint8_t*)&Monitor_info_, Monitor_info_.len);
}


void TcpClient::Send(uint8_t* data, uint32_t size)
{
    int len = 0;
    int index = 0;
    while (index != size)
    {
        len = send(sockfd_, data + index, size - index, 0);
        if (len < 0) break;
        index += len;
    }
}


